package com.takeshequ.feeds;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.AnnotationUtils;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.annotation.view.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.takeshequ.Constants;
import com.takeshequ.PullAndLoadListView;
import com.takeshequ.PullToRefreshListView.OnRefreshListener;
import com.takeshequ.R;
import com.takeshequ.SMApplication;
import com.takeshequ.chat.ExpressionUtil;
import com.takeshequ.homepage.HomePageActivity;
import com.takeshequ.main.BasicFragment;
import com.utils.HttpClientUtils;
import com.utils.HttpClientUtils.HttpResponseHandler;

public class FeedsFragment extends BasicFragment implements
		AdapterView.OnItemClickListener {
	private static final String TAG = "NearestFragment";
	static Context context = null;
	private static Gson gson;
	private static int pageNumber = 1;
	private View processView;
	private View nomessageView;
	private Map<Integer, View> viewMap = new HashMap<Integer, View>();

	public static FeedsFragment newInstance(Context con, SMApplication app) {
		context = con;
		gson = new Gson();
		FeedsFragment newFragment = new FeedsFragment();
		return newFragment;

	}

	private static ArrayList<FeedsListItem> items;
	static {
		items = new ArrayList<FeedsListItem>();
		items.add(new FeedsListItem());

	}

	private PullAndLoadListView listView;
	private FeedsAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private void getListItems(final AsyncHttpResponseHandler handler) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("pageNumber", String.valueOf(pageNumber));

		HttpClientUtils.get("listFriendBehavior", params,
				new HttpResponseHandler() {

					@Override
					public void handler(String response) {
						handler.onSuccess(response);
					}
				});
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.feeds, container, false);
		processView = view.findViewById(R.id.feeds_list_view_process);
		nomessageView = view.findViewById(R.id.feeds_list_view_nomessage);
		listView = (PullAndLoadListView) view
				.findViewById(R.id.feeds_list_view);
		listView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				listView.postDelayed(new Runnable() {
					@Override
					public void run() {
						getListItems(new RefreshAsyncHttpResponseHandler());
						listView.onRefreshComplete();
					}
				}, 2000);
			}
		});
		adapter = new FeedsAdapter(inflater);
		listView.setAdapter(adapter);
		getListItems(new RefreshAsyncHttpResponseHandler());
		return view;
	}

	class RefreshAsyncHttpResponseHandler extends AsyncHttpResponseHandler {

		@Override
		public void onStart() {
			super.onStart();
			System.out.println("开始");
			processView.setVisibility(View.VISIBLE);
			nomessageView.setVisibility(View.VISIBLE);
		}

		@Override
		public void onSuccess(String response) {
			System.out.println("结束");
			try {
				JSONObject jsonObject = new JSONObject(response);
				if (jsonObject.getJSONArray("behaviorList").length() > 0) {
					items = gson.fromJson(jsonObject.getString("behaviorList"),
							new TypeToken<List<FeedsListItem>>() {
							}.getType());
					adapter.notifyDataSetChanged();
					nomessageView.setVisibility(View.GONE);
				}
				processView.setVisibility(View.GONE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void resetPageNumber() {
		pageNumber = 1;
	}

	private void pageNumberAddOne() {
		pageNumber = pageNumber + 1;
	}

	private void pageNumberReduceOne() {
		if (pageNumber > 1) {
			pageNumber = pageNumber - 1;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		// Toast.makeText(context, adapter.getItem(i).getNickName(),
		// Toast.LENGTH_SHORT).show();
	}

	class FeedsAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		private class ViewHolder {
			public TextView nickName, content, distance, time, loveNumber,
					chatNumber, age, sourceFrom;
			public ImageView headImage, picImage, genderImage, loveImage;
		}

		public FeedsAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (items.size() > position) {
				View view = viewMap.get(position);
				final ViewHolder holder;
				if (view == null) {
					view = inflater.inflate(R.layout.feeds_list_item, parent,
							false);
					holder = new ViewHolder();
//					AnnotationUtils.initView(context, view, holder);
					holder.picImage = (ImageView) view
							.findViewById(R.id.feeds_list_view_pic);
					holder.nickName = (TextView) view
							.findViewById(R.id.feeds_list_view_nickName);
					holder.nickName.getPaint().setFakeBoldText(true);
					holder.headImage = (ImageView) view
							.findViewById(R.id.feeds_list_view_head_img);
					holder.distance = (TextView) view
							.findViewById(R.id.feeds_list_item_distance);
					holder.content = (TextView) view
							.findViewById(R.id.feeds_list_view_content);
					holder.time = (TextView) view
							.findViewById(R.id.feeds_list_view_time);
					holder.age = (TextView) view
							.findViewById(R.id.feeds_item_age);
					holder.genderImage = (ImageView) view
							.findViewById(R.id.fedds_item_gender_img);
					holder.chatNumber = (TextView) view
							.findViewById(R.id.feeds_list_item_chat_number);
					holder.loveNumber = (TextView) view
							.findViewById(R.id.feeds_list_item_love_number);
					holder.sourceFrom = (TextView) view
							.findViewById(R.id.feeds_list_item_source);
					holder.loveImage = (ImageView) view
							.findViewById(R.id.feeds_list_view_love_btn);
					view.setTag(holder);
					viewMap.put(position, view);
				} else {
					holder = (ViewHolder) view.getTag();
				}

				final FeedsListItem feed = items.get(position);
				holder.nickName.setText(feed.getNickName());
				FinalBitmap.create(context).display(holder.headImage,
						feed.getHeadImage());

				SpannableString spannableString = ExpressionUtil
						.getExpressionString(context, feed.getCont());
				holder.content.setText(spannableString);
				holder.distance.setText(feed.getDistance() + " KM");
				holder.time.setText(feed.getCreateDateString());
				if (feed.getImage() instanceof Object) {
					FinalBitmap.create(context).display(holder.picImage,
							feed.getImage());
				}
				if (feed.getSex() instanceof String) {
					if (feed.getSex().equals("m")) {
						holder.genderImage.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.friends_item_male));
					} else {
						holder.genderImage.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.friends_item_female));
					}
				}
				holder.headImage.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Constants.selectMemberId = feed.getMemberId();
						startActivity(new Intent(context,
								HomePageActivity.class));
					}
				});
				holder.age.setText(feed.getAge());
				holder.chatNumber.setText(feed.getCommentCount());
				holder.loveNumber.setText(feed.getPraiseCount());
				holder.sourceFrom.setText(feed.getSourcefrom());
				view.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context,
								FeedsDetailActivity.class);
						intent.putExtra("behaviorId", feed.getBehaviorId());
						startActivity(intent);
					}
				});

				holder.loveImage.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						Map<String, String> params = new HashMap<String, String>();
						params.put("memberId", Constants.memberId);
						params.put("nickName", Constants.member.getNickName());
						params.put("headImage", Constants.member.getHeadImage());
						params.put("behaviorId", feed.getBehaviorId());
						params.put("cont", "");
						params.put("commentType", "2");
						HttpClientUtils.post("/praiseBehavior", params,
								new HttpResponseHandler() {

									@Override
									public void handler(String response) {
										try {
											JSONObject jsonObject = new JSONObject(
													response);
											holder.loveNumber.setText(jsonObject
													.getString("totalCount"));
											Toast.makeText(context, "已赞", 2000)
													.show();
										} catch (JSONException e) {
											e.printStackTrace();
										}

									}
								});
					}
				});
				return view;
			}
		
			return null;
		}
	}

	@Override
	public void show() {
		getListItems(new RefreshAsyncHttpResponseHandler());
	}

}